//
//  SNFootDetailViewController.m
//  project
//
//  Created by 黄建华 on 2018/11/8.
//  Copyright © 2018年 黄建华. All rights reserved.
//

#import "SNFoodDetailViewController.h"
#import "SNFoodChartView.h"

@interface SNFoodDetailViewController ()

@property (nonatomic, strong) SNFoodChartView *ChartView;
@property (nonatomic, strong) NSMutableArray  *modelArray;
@property (nonatomic, assign) SelectDateType  lastType;

@end

@implementation SNFoodDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.leftButton.hidden = NO;
    [self.leftButton setImageNormal:@"进入"];
    
    SNShadowView *shadowLine = [[SNShadowView alloc] init];
    shadowLine.frame = SNFRAME(0,20+FitSimpleIpx(0, 20) + 44, HHHWIDTH, 0);
    [shadowLine showWithType:1];
    [self.view addSubview:shadowLine];
    
    _ChartView                 = [[SNFoodChartView alloc] initWithFrame:SNFRAME(0, 70 +FitSimpleIpx(0, 20), HHHWIDTH, HHHHEIGHT *0.4 -FitSimpleIpx(0, 20))];
    _ChartView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_ChartView];
    
    NSArray *array1 = [NSArray arrayWithObjects:SN_Text(@"日均热量赤字"), SN_Text(@"运动达标天数"), SN_Text(@"摄入合格天数"), SN_Text(@"日均摄入热量"), SN_Text(@"单日最高摄入"), SN_Text(@"未打卡天数"), nil];
    
    CGFloat height      = FitSimpleSize(75, 80, 100, 120, 130);
    CGFloat labelHeight = FitSimpleSize(0, 0, 10, 20, 27);
    UIView  *line0      = [[UIView alloc] init];
    line0.frame           = SNFRAME(0, _ChartView.origin.y + HHHHEIGHT *0.43, HHHWIDTH, 5.0);
    line0.backgroundColor = SNCOLORGRAYLINE;
    [self.view addSubview:line0];
    
    UIView *line1 = [[UIView alloc] init];
    line1.frame           = SNFRAME(0, _ChartView.origin.y + HHHHEIGHT *0.43 + height, HHHWIDTH, 1);
    line1.backgroundColor = SNCOLORGRAYLINE;
    [self.view addSubview:line1];
    
    UIView *line2 = [[UIView alloc] init];
    line2.frame           = SNFRAME(0, _ChartView.origin.y + HHHHEIGHT *0.43 + height*2, HHHWIDTH, 5.0);
    line2.backgroundColor = SNCOLORGRAYLINE;
    [self.view addSubview:line2];
    
    UIView *line3 = [[UIView alloc] init];
    line3.frame           = SNFRAME(HHHWIDTH /3, _ChartView.origin.y + HHHHEIGHT *0.43, 1, height*2);
    line3.backgroundColor = SNCOLORGRAYLINE;
    [self.view addSubview:line3];
    
    UIView *line4 = [[UIView alloc] init];
    line4.frame           = SNFRAME(HHHWIDTH /3 *2, _ChartView.origin.y + HHHHEIGHT *0.43, 1, height*2);
    line4.backgroundColor = SNCOLORGRAYLINE;
    [self.view addSubview:line4];
    
    for (int i = 0; i < 6; i++) {
        UILabel *unitLabel = [[UILabel alloc] init];
        unitLabel.text          = array1[i];
        unitLabel.textColor     = SNCOLORGRAY;
        unitLabel.font = SNSFONT(SNFITFONTSIZE(14));
        unitLabel.numberOfLines = 0;
        NSDictionary *attribute1 = @{NSFontAttributeName: unitLabel.font};
        //计算实际frame大小，并将label的frame变成实际大小
        CGSize labelsize1 = [unitLabel.text boundingRectWithSize:CGSizeMake(HHHWIDTH /3-2, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute1 context:nil].size;
        if (i < 3) {
            if (labelsize1.width < HHHWIDTH /3-2 ) {
                unitLabel.frame = SNFRAME(HHHWIDTH /3 *i+1, labelHeight +_ChartView.origin.y + HHHHEIGHT *0.43 + 40, HHHWIDTH /3-2, labelsize1.height);
            } else {
                unitLabel.frame = SNFRAME(HHHWIDTH /3 *i+1, labelHeight +_ChartView.origin.y + HHHHEIGHT *0.43 + 40, labelsize1.width, labelsize1.height);
            }
            
        } else {
            if (labelsize1.width < HHHWIDTH /3-2) {
                unitLabel.frame = SNFRAME(HHHWIDTH /3 *i+1 - HHHWIDTH, labelHeight +_ChartView.origin.y + HHHHEIGHT *0.43 + 40 + height, HHHWIDTH /3-2, labelsize1.height);
            } else {
                unitLabel.frame = SNFRAME(HHHWIDTH /3 *i+1 - HHHWIDTH, labelHeight +_ChartView.origin.y + HHHHEIGHT *0.43 + 40 + height, labelsize1.width, labelsize1.height);
            }
        }
        
        unitLabel.textAlignment = NSTextAlignmentCenter;
        [self.view addSubview:unitLabel];
    }
    // 数值显示Label
    for (int i = 0; i < 6; i++) {
        UILabel *unitLabel = [[UILabel alloc] init];
        unitLabel.textAlignment = NSTextAlignmentCenter;
        unitLabel.textColor     = SNCOLORBLACK;
        unitLabel.font          = SNFONT(13.0);
        unitLabel.tag           = 100 + i;
        if (i < 3) {
            unitLabel.frame = SNFRAME(HHHWIDTH /3 *i, labelHeight +_ChartView.origin.y + HHHHEIGHT *0.43 + 40 - 22, HHHWIDTH /3, 20);
        } else {
            unitLabel.frame = SNFRAME(HHHWIDTH /3 *i - HHHWIDTH, labelHeight +_ChartView.origin.y + HHHHEIGHT *0.43 + 40 + height - 22, HHHWIDTH /3, 20);
        }
        [self.view addSubview:unitLabel];
    }
    
    [self selectType:SelectDateWeek];
}

- (BOOL)isFoodCurrentDateString:(NSString *)currentDateString foodBeginDateString:(NSString*)firstDateString;
{
    BOOL ok = NO;
    int             comparisonResult;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *oneDayStr = firstDateString;
    NSString *anotherDayStr = currentDateString;
    NSDate *dateOne = [dateFormatter dateFromString:oneDayStr];
    NSDate *dateTwo = [dateFormatter dateFromString:anotherDayStr];
    NSComparisonResult result = [dateOne compare:dateTwo];
    switch (result) { //date02比date01大
        case NSOrderedAscending:
            comparisonResult = 1;              // 选择日期 是未来日期
            break;
            //date02比date01小
        case NSOrderedDescending:              // 选择日期 是过去日期
            comparisonResult = -1;
            break;
            //date02=date01
        case NSOrderedSame:
            comparisonResult = 0;
            break;
        default:
            break;
    }
    
    if (comparisonResult == 1 || comparisonResult == 0) {
        ok = YES;
    }
    
    NSString *oneDayStr2 = [[NSDate date]dateToDayString];
    NSString *anotherDayStr2 = currentDateString;
    NSDate *dateOne2 = [dateFormatter dateFromString:oneDayStr2];
    NSDate *dateTwo2 = [dateFormatter dateFromString:anotherDayStr2];
    NSComparisonResult result2 = [dateOne2 compare:dateTwo2];
    int             comparisonResult2;
    switch (result2) {
        case NSOrderedAscending:
            comparisonResult2 = 1;
            break;
        case NSOrderedDescending:
            comparisonResult2 = -1;
            break;
        case NSOrderedSame:
            comparisonResult2 = 0;
            break;
        default:
            break;
    }
    
    if (comparisonResult2 == 1) {
        ok = NO;
    }
    
    return ok;
}

- (void)selectType:(SelectDateType)type {
    //    NSLog(@"周月年选择了>>>>>>%d",type);
    _lastType = type;
    NSString *nowDateString = [[NSDate date] dateToDayString];
    SportModel     *model = [SportModel getSportModelFromDBWith:SN_PublicClass.selectDate];
    NSMutableArray *array = [NSMutableArray array];
    NSMutableArray *calorArray = [NSMutableArray array];
    
    if (type == SelectDateDay) {
        array = [NSMutableArray arrayWithArray:model.stepArray];
    }
    
    NSString *foodFirstString = SN_FoodClass.firstCreate;
    
    NSInteger typeT = 1;
    if (type == SelectDateWeek) {
        typeT = 1;
    }else if(type == SelectDateMonth)
    {
        typeT = 2;
    }
    else if (type == SelectDateYear)
    {
        typeT = 3;
    }
    // 这里切换为卡路里
    if (type == SelectDateWeek || type == SelectDateMonth) {
        NSInteger count = 0;
        if (typeT == 1) {
            count = 7;
        }
        if (typeT == 2) {
            count = SN_PublicClass.selectDate.daysInMonth;
        }
        for (int i = 0; i < count; i++) {
            NSDate   *first       = [SN_PublicClass getMonthBeginAndEndWith:SN_PublicClass.selectDate withType:typeT];
            NSDate   *Date        = [first dateAfterDay:i];
            NSString *firstString = [Date dateToDayString];
            
            NSString *sss         = [NSString stringWithFormat:@"SELECT calory FROM SportModel WHERE dateString ='%@'and dateString <='%@' and user_id = '%@' and dateString >='%@' and isFood = 1 and dateString <='%@'", firstString, [[NSDate date]dateToDayString], SN_USER.user_id,foodFirstString,nowDateString];
            NSString *stepValue   = [[SportModel getUsingLKDBHelper]executeScalarWithSQL:sss arguments:nil];
            
            NSString *www = [NSString stringWithFormat:@"SELECT baseCalor FROM FootModel WHERE dateString ='%@'and dateString <='%@' and user_id = '%@' and dateString >= '%@' and dateString <='%@' and currentCalor >0", firstString, [[NSDate date]dateToDayString], SN_USER.user_id,foodFirstString,nowDateString];
            NSString *baseCalorValue   = [[FoodModel getUsingLKDBHelper]executeScalarWithSQL:www arguments:nil];
            // 运动消耗
            NSInteger baseCalor = baseCalorValue.integerValue;

            NSInteger calor =  stepValue.integerValue + baseCalor;
            [array addObject:StrByInt(calor)];
            //摄入消耗
            NSString*fff = [NSString stringWithFormat:@"SELECT currentCalor FROM FootModel WHERE dateString ='%@'and dateString <='%@' and user_id = '%@' and dateString >='%@' and dateString <='%@' and currentCalor >0", firstString, [[NSDate date]dateToDayString], SN_USER.user_id,foodFirstString,nowDateString];
            NSString *currentCalor   = [[FoodModel getUsingLKDBHelper]executeScalarWithSQL:fff arguments:nil];
            [calorArray addObject:StrByInt(currentCalor.integerValue)];
            
//            BOOL isFood = [self isFoodCurrentDateString:firstString foodBeginDateString:foodFirstString];
//            if (isFood) {
//                NSString *sss         = [NSString stringWithFormat:@"SELECT calory FROM SportModel WHERE dateString ='%@'and dateString <='%@' and user_id = '%@'", firstString, [[NSDate date]dateToDayString], SN_USER.user_id];
//                NSString *stepValue   = [[SportModel getUsingLKDBHelper]executeScalarWithSQL:sss arguments:nil];
//
//                NSString *www = [NSString stringWithFormat:@"SELECT baseCalor FROM FootModel WHERE dateString ='%@'and dateString <='%@' and user_id = '%@'", firstString, [[NSDate date]dateToDayString], SN_USER.user_id];
//                NSString *baseCalorValue   = [[FoodModel getUsingLKDBHelper]executeScalarWithSQL:www arguments:nil];
//                // 运动消耗
//                NSInteger baseCalor = baseCalorValue.integerValue;
//
////                if ([firstString isEqualToString:[[NSDate date]dateToDayString]]) {
////                    NSInteger currentMin =  [NSDate getCurrentMinTotal];
////                    baseCalor = 1.0*currentMin/1440 *baseCalor;
////                }
//                NSInteger calor =  stepValue.integerValue + baseCalor;
//                [array addObject:StrByInt(calor)];
//
//                // 摄入消耗
//                NSString*fff = [NSString stringWithFormat:@"SELECT currentCalor FROM FootModel WHERE dateString ='%@'and dateString <='%@' and user_id = '%@'", firstString, [[NSDate date]dateToDayString], SN_USER.user_id];
//                NSString *currentCalor   = [[FoodModel getUsingLKDBHelper]executeScalarWithSQL:fff arguments:nil];
//                [calorArray addObject:StrByInt(currentCalor.integerValue)];
//            }
//            else
//            {
//            [array addObject:@"0"];
//            [calorArray addObject:@"0"];
//            }
        }
    }
    
    if (type == SelectDateYear) {
        for (int i = 1; i <= 12; i++) {
            NSString *monthStep  = [NSString stringWithFormat:@"SELECT SUM(calory) AS OrderTotal FROM SportModel WHERE yearCount =%d and monthCount = %d  and dateString <='%@' and user_id = '%@' and dateString>='%@' and isFood =1 and dateString <='%@'", model.yearCount, i, [[NSDate date]dateToDayString], SN_USER.user_id,foodFirstString,nowDateString];
            NSString *monthSteps = [[SportModel getUsingLKDBHelper]executeScalarWithSQL:monthStep arguments:nil];
            
            NSString *www  = [NSString stringWithFormat:@"SELECT SUM(baseCalor) AS OrderTotal FROM FootModel WHERE yearCount =%d and monthCount = %d  and dateString <='%@' and user_id = '%@' and dateString>='%@' and dateString <='%@' and currentCalor >0", model.yearCount, i, [[NSDate date]dateToDayString], SN_USER.user_id,foodFirstString,nowDateString];
            NSString *baseCalorValue = [[FoodModel getUsingLKDBHelper]executeScalarWithSQL:www arguments:nil];
            NSInteger baseCalor = baseCalorValue.integerValue;
            
            NSInteger calor =  monthSteps.integerValue + baseCalor;
            [array addObject:StrByInt(calor)];
            
            NSString *fff  = [NSString stringWithFormat:@"SELECT SUM(currentCalor) AS OrderTotal FROM FootModel WHERE yearCount =%d and monthCount = %d  and dateString <='%@' and user_id = '%@' and dateString>='%@' and dateString <='%@' and currentCalor >0", model.yearCount, i, [[NSDate date]dateToDayString], SN_USER.user_id,foodFirstString,nowDateString];
            NSString *currentCalor = [[FoodModel getUsingLKDBHelper]executeScalarWithSQL:fff arguments:nil];
             [calorArray addObject:StrByInt(currentCalor.integerValue)];
        }
    }

    [_ChartView UpdateViewWithType:type withArray:array withArray:calorArray];
    [self updateValueLabel:type];
}

- (NSInteger)getTimeWithBegin:(NSString*)startTime andEnd:(NSString *)endTime
{
    NSInteger time = 0;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *startDate = [dateFormatter dateFromString:startTime];
    NSDate *endDate = [dateFormatter dateFromString:endTime];
    //利用NSCalendar比较日期的差异
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    NSCalendarUnit unit = NSCalendarUnitDay;//只比较天数差异
    //比较的结果是NSDateComponents类对象
    NSDateComponents *delta = [calendar components:unit fromDate:startDate toDate:endDate options:0];
    //打印
    NSLog(@"开始日期>>>%@ 结束日期>>%@ 相差%d",startTime,endTime,delta.day);
    time = delta.day + 1;
    return time;
}

// 数据统计
- (void)updateValueLabel:(SelectDateType)type {
    NSString *nowDateString = [[NSDate date] dateToDayString];
    NSMutableArray *array2 = [NSMutableArray array];
    NSString *foodFirstString = SN_FoodClass.firstCreate;
    NSArray *time = [SN_PublicClass getBeginDateStringAndEndWith:SN_PublicClass.selectDate withType:type];
    
    /*******************************日均赤字******************************************/
    NSString *aveSportCalorS = [NSString stringWithFormat:@"SELECT AVG(calory) AS OrderTotal FROM SportModel WHERE dateString >='%@' and dateString <='%@' and user_id = '%@' and isFood = 1 and dateString <='%@'", [time firstObject], [time lastObject], SN_USER.user_id,nowDateString];
    NSString *aveSportCalor = [[SportModel getUsingLKDBHelper]executeScalarWithSQL:aveSportCalorS arguments:nil];

    NSString *aveBaseCalorS = [NSString stringWithFormat:@"SELECT AVG(baseCalor) AS OrderTotal FROM FootModel WHERE dateString >='%@' and dateString <='%@' and user_id = '%@' and currentCalor >0 and dateString <='%@'", [time firstObject], [time lastObject], SN_USER.user_id,nowDateString];
    NSString *aveBaseCalor = [[FoodModel getUsingLKDBHelper]executeScalarWithSQL:aveBaseCalorS arguments:nil];
    
    NSString *currentCalorS = [NSString stringWithFormat:@"SELECT AVG(currentCalor) AS OrderTotal FROM FootModel WHERE dateString >='%@' and dateString <='%@' and user_id = '%@' and currentCalor >0 and dateString <='%@'", [time firstObject], [time lastObject], SN_USER.user_id,nowDateString];
    
    NSString *currentCalor = [[FoodModel getUsingLKDBHelper]executeScalarWithSQL:currentCalorS arguments:nil];
    NSInteger add = aveSportCalor.integerValue + aveBaseCalor.integerValue;
    NSInteger resultCalur = add - currentCalor.integerValue;
    if (resultCalur >0) {
        [array2 addObject:[NSString stringWithFormat:@"＋%d",resultCalur]];
    }
    else if(resultCalur == 0)
    {
        [array2 addObject:@"0"];
    }
    else
    {
        [array2 addObject:[NSString stringWithFormat:@"−%d",-resultCalur]];
    }

    /****************************每日达标天数*********************************************/
    NSString *finish  = [NSString stringWithFormat:@"SELECT SUM(stepFinish) AS OrderTotal FROM SportModel WHERE dateString >='%@' and dateString <='%@' and user_id = '%@' and stepquality = 1 and step >0 and dateString <='%@' and isFood = 1", [time firstObject], [time lastObject], SN_USER.user_id,nowDateString];
    NSString *finishs = [[SportModel getUsingLKDBHelper]executeScalarWithSQL:finish arguments:nil];
    [array2 addObject:StrByInt(finishs.intValue)];
    /**************************** 摄入合格天数*********************************************/
    NSString *eatFinishS = [NSString stringWithFormat:@"SELECT SUM(finishQuality) AS OrderTotal FROM FootModel WHERE dateString >='%@' and dateString <='%@' and user_id = '%@' and currentCalor >0 and dateString <='%@'", [time firstObject], [time lastObject], SN_USER.user_id,nowDateString];
    NSString *eatFinish = [[FoodModel getUsingLKDBHelper]executeScalarWithSQL:eatFinishS arguments:nil];
    [array2 addObject:StrByInt(eatFinish.intValue)];
    
//    NSString *where = [NSString stringWithFormat:@"dateString <='%@' and user_id ='%@' and dateString >='%@'",[time lastObject],SN_USER.user_id,[time firstObject]];
//    NSArray *foodArray = [FoodModel searchWithWhere:where orderBy:@"dateString" offset:-1 count:0];
    
    /*****************************日均摄入热量********************************************/
    NSInteger aveCurrentCalor = currentCalor.integerValue;
     [array2 addObject:StrByInt(aveCurrentCalor)];
    /*************************************************************************/

    /*****************************单日最高摄入********************************************/
    NSString *maxCurrentCalorS = [NSString stringWithFormat:@"SELECT MAX(currentCalor) AS OrderTotal FROM FootModel WHERE dateString >='%@' and dateString <='%@' and user_id = '%@' and currentCalor >0 and dateString <='%@'", [time firstObject], [time lastObject], SN_USER.user_id,nowDateString];
    NSString *maxCurrentCalor = [[SportModel getUsingLKDBHelper]executeScalarWithSQL:maxCurrentCalorS arguments:nil];
    [array2 addObject:StrByInt(maxCurrentCalor.intValue)];
    
    /*******************************未打卡天数********************************************/
    // 开始的时间截止今天  - 打卡天数 = 未打卡天数
    NSString *unFinishS = [NSString stringWithFormat:@"SELECT SUM(finish) AS OrderTotal FROM FootModel WHERE dateString >='%@' and dateString <='%@' and user_id = '%@' and dateString >='%@' and currentCalor > 0 and dateString <='%@'", [time firstObject], [time lastObject], SN_USER.user_id,foodFirstString,nowDateString];
    NSString *unFinish = [[FoodModel getUsingLKDBHelper]executeScalarWithSQL:unFinishS arguments:nil];
   
    // 计算相差间隔
    NSString *start = [time firstObject];
    NSString *end = [time lastObject];
    NSInteger dayInterval = [self getTimeWithBegin:start andEnd:end];
    
     [array2 addObject:StrByInt(dayInterval -unFinish.intValue)];

     /*******************************未打卡天数********************************************/
    
    if (array2.count > 0) {
        for (UILabel *label in self.view.subviews) {
            if ([label isKindOfClass:[UILabel class]]) {
                if (label.tag >= 100) {
                    label.text = array2[label.tag - 100];
                    if (label.tag == 100) {
                        NSString *valueS = [label.text substringToIndex:1];
                        if ([valueS isEqualToString:@"−"]) {
                        [label setAttributedText:[SN_PublicClass labelSelfText:label.text withChangeText:@"−" withFontsize:13.0 withChangeColor:[UIColor redColor]]];
                        }
                    }
                }
            }
        }
    }
}

- (void)updateView:(KKBLEAcceptType)type {
    if (type == KKBLEAcceptTypeRealtimeSport || type == KKBLEAcceptTypeDataSport) {
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayUpdateView) object:nil];
        [self performSelector:@selector(delayUpdateView) withObject:nil afterDelay:3.0];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayUpdateView) object:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)delayUpdateView {
    [self selectType:_lastType];
}

- (void)functionSetLeft
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)functionSetRight
{
    
}

@end
